package com.nowcoder.community.service;

import com.nowcoder.community.dao.LoginTicketMapper;
import com.nowcoder.community.dao.UserMapper;
import com.nowcoder.community.entity.LoginTicket;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.MailClient;
import com.nowcoder.community.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.nio.channels.SelectableChannel;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>Title: UserService</p>
 * <p>author 12427</p>
 *
 * @version ver1.0
 * @date 2022/7/3 9:17
 */
@Service
public class UserService implements CommunityConstant {

    @Autowired
    private UserMapper userMapper ;

    @Autowired
    private MailClient mailClient ;

    @Autowired
    private TemplateEngine templateEngine ;

    @Autowired
    private RedisTemplate redisTemplate ;


    @Value("${community.path.domain}")
    private String domain ;

    @Value("${server.servlet.context-path}")
    private String contextPath ;

//    @Autowired
//    private  LoginTicketMapper loginTicketMapper ;



    public User findUserById(int id){
        User user = getCache(id) ;
        if(user == null ){
            user = initCache(id) ;
        }
        return user ;
    }

    public Map<String,Object> register(User user){
        Map<String,Object> map = new HashMap<>() ;

        // 先对参数进行判断
        // 1. 空值处理
        if(user == null) {
            throw new IllegalArgumentException("用户值参数为空!") ;
        }
        if(StringUtils.isBlank(user.getUsername())){
            map.put("usernameMsg" , "账号不能为空!") ;
            return map ;
        }

        if(StringUtils.isBlank(user.getPassword())){
            map.put("passwordMsg" , "密码不能为空!") ;
            return map ;
        }
        if(user.getPassword().length() < 8 ){
            map.put("passwordMsg" , "密码长度不应低于8位!") ;
            return map ;
        }

        if(StringUtils.isBlank(user.getEmail())){
            map.put("emailMsg" , "邮箱不能为空!") ;
            return map ;
        }

        // 2. 验证不重复
        User u = userMapper.selectByName(user.getUsername());
        // 验证账号
        if(u != null) {
            map.put("usernameMsg" , "该账号已存在!") ;
            return map ;
        }
        // 验证邮箱
        u = userMapper.selectByEmail(user.getEmail());
        if(u != null) {
            map.put("emailMsg" , "该邮箱已被注册!") ;
            return map;
        }

        // 注册用户
        user.setSalt(CommunityUtil.generateUUID().substring(0,5));
        user.setPassword(CommunityUtil.md5(user.getPassword() +user.getSalt() ));
        user.setType(0);
        user.setStatus(0);
        user.setActivationCode(CommunityUtil.generateUUID());

        user.setHeaderUrl("http://rh3m7avkx.hb-bkt.clouddn.com/f0dc1cb01d734cbb8f3df70ed10fdc9f");


        user.setCreateTime(new Date());
        userMapper.insertUser(user) ;


        // 激活邮件的发送
        Context context = new Context() ;
        context.setVariable("email" , user.getEmail() );


        // http://hocalhost:8080/community/activation/{id}/code
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode() ;

        context.setVariable("url" , url);

        String content = templateEngine.process("/mail/activation" , context) ;
        mailClient.sendMail(user.getEmail() , "激活账号" ,content);

        return map ; // 如果是空的，表示ok
    }


    public int activation(int userId , String code){
        User user = userMapper.selectById(userId) ;
        if(user.getStatus() == 1){
            return ACTIVATION_REPEATE ;
        }else if(user.getActivationCode().equals(code)){
            userMapper.updateStatus(userId , 1) ;
            clearCache(userId);
            return ACTIVATION_SUCCESS ;
        }else {
            return ACTIVATION_FAILURE ;
        }
    }


    public Map<String,Object> login(String username , String password ,  int expiredSeconds){

        Map<String,Object> map = new HashMap<>() ;

        // 空值处理
        if(StringUtils.isBlank(username)){
            map.put("usernameMsg" , "账号不能为空");
            return map ;
        }

        if(StringUtils.isBlank(password)){
            map.put("passwordMsg","密码不能为空");
            return  map;
        }

        // 合法性的验证
        User user  = userMapper.selectByName(username);
        if(user == null){
            map.put("usernameMsg" , "该用户不存在!");
            return map ;
        }
        if(user.getStatus() == 0 ) {
            map.put("usernameMsg" , "该账号未激活!") ;
            return  map ;
        }


        password = CommunityUtil.md5(password + user.getSalt()) ;
        if(!password.equals(user.getPassword())){
            map.put("passwordMsg","密码不正确");
            return  map;
        }

        // 生成登录凭证
        LoginTicket loginTicket = new LoginTicket() ;
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + (long)expiredSeconds * 1000));
//        loginTicketMapper.insertLoginTicket(loginTicket) ;
        String redisKey= RedisKeyUtil.getTicketKey(loginTicket.getTicket()) ;
        redisTemplate.opsForValue().set(redisKey , loginTicket); // redis 自动序列化成json字符串




        map.put("ticket" , loginTicket.getTicket()) ;
        return map ;
    }

    public void logout(String ticket){
//        loginTicketMapper.updateStatus(ticket,1) ;
        String redisKey = RedisKeyUtil.getTicketKey(ticket) ;
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
        loginTicket.setStatus(1);
        redisTemplate.opsForValue().set(redisKey , loginTicket);
    }

    // 若干工具方法
    public LoginTicket findLoginTicket(String ticket){
//        return loginTicketMapper.selectByTicket(ticket) ;
        String redisKey = RedisKeyUtil.getTicketKey(ticket) ;
        return (LoginTicket) redisTemplate.opsForValue().get(redisKey);
    }

    public int updateHeader(int userId , String headerUrl){
//        return userMapper.updateHeader(userId,headerUrl) ;
        int rows = userMapper.updateHeader(userId, headerUrl);

        clearCache(userId);

        return rows ;

    }

    public User findUserByName(String username){
        return userMapper.selectByName(username) ;
    }

    public User findUserByEmail(String email){
        return userMapper.selectByName(email) ;
    }

    // 忘记密码-重置密码
    public Map<String,Object> resetPassword(String email, String password) {
        Map<String,Object> map = new HashMap<>() ;

        // 空值处理
        if(StringUtils.isBlank(email)) {
            map.put("emailMsg" , "邮箱不能为空") ;
            return map ;
        }

        if(StringUtils.isBlank(password)){
            map.put("passwordMsg" , "密码不能为空") ;
            return map;
        }

        // 合法性验证
        // 具体逻辑是根据邮箱修改对应用户的密码
        User user = userMapper.selectByEmail(email);
        if(user == null) {
            map.put("emailMsg" , "该邮箱未注册!");
            return map ;
        }


        // 重置密码
        password = CommunityUtil.md5(password + user.getSalt()) ;
        userMapper.updatePassword(user.getId() , password) ;

        map.put("user" , user) ;
        return map ;

    }



    // 修改密码
    public Map<String,Object>  updatePassword(int userId,  String oldPassword , String  newPassword){
        Map<String,Object> map = new HashMap<>() ;

        // 空值处理
        if(StringUtils.isBlank(oldPassword)){
            map.put("oldPasswordMsg" , "原密码不能为空") ;
            return map ;
        }
        if(StringUtils.isBlank(newPassword)){
            map.put("newPasswordMsg" , "新密码不能为空") ;
            return map ;
        }

        // 验证原始密码
        User user = userMapper.selectById(userId) ;
        oldPassword = CommunityUtil.md5(oldPassword + user.getSalt()) ;
        if(!user.getPassword().equals(oldPassword)){
            map.put("oldPasswordMsg" , "原密码输入有误") ;
            return map ;
        }

        // 更新密码
        newPassword = CommunityUtil.md5(newPassword + user.getSalt()) ;
        userMapper.updatePassword(userId , newPassword ) ;

        return map;

    }

    // 1. 优先从缓存中取值

    private User getCache(int userId){
        String redisKey  = RedisKeyUtil.getUserKey(userId) ;
        return (User) redisTemplate.opsForValue().get(redisKey);
    }

    // 2. 取不到就初始化缓存
    private User initCache(int userId) {
        User user = userMapper.selectById(userId);
        String redisKey = RedisKeyUtil.getUserKey(userId) ;
        redisTemplate.opsForValue().set(redisKey , user , 3600 , TimeUnit.SECONDS)  ;
        return user ;
    }


    // 3. 数据变更清除缓存
    private void clearCache(int userId){
        String redisKey = RedisKeyUtil.getUserKey(userId) ;
        redisTemplate.delete(redisKey) ;
    }

    public Collection<? extends GrantedAuthority> getAuthorities(int userId){
        User user = this.findUserById(userId) ;

        List<GrantedAuthority> list = new ArrayList<>() ;
        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                // 根据type返回权限字符串
                switch (user.getType()){
                    case 1 :
                        return AUTHORITY_ADMIN ;
                    case 2 :
                        return AUTHORITY_MODERATOR ;
                    default:
                        return AUTHORITY_USER ;
                }
            }
        }) ;
        return list ;
    }


}
